<?php
/**
 *  临时一次性脚本
 *
 * User: gongming
 * Date: 2018/3/2
 * Time: 下午13:49
 */

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\Db;
use think\Cache;
use think\Exception;
use think\Log;
use think\Queue;

class Test extends Command {
    // 类中configure()函数命令行中使用list命令列出所有任务的时候回显出的摘要提示
    // cmd执行，进入根目录
    // php think clearSpiderRedisData
    // /usr/local/qqwebsrv/php/bin/php /data/phpAdmin/think test
    protected function configure() {
        // 设置命令名称 以及 命令说明
        $this->setName('test')->setDescription('test')
            ->addArgument('start', Argument::OPTIONAL, '', null)
            ->addArgument('end', Argument::OPTIONAL, '', null);
    }

    // execute()函数是要执行的命令，这里可以直接写需要完成的任务或者调用类中任务方法。
    protected function execute(Input $input, Output $output) {
        //$this->test($input, $output);
        //$this->regNewUserInfo($input, $output);
        //$this->selectUserCate($input, $output);
        //$this->checkUserInfoStatus($input, $output);
        //$this->checkRecList($input, $output);
        //$this->updateUsersNickname();
        //$this->guideData();
        //推荐补贴修复
        //$this->fixWallet();
        //历史文章收入合并表
//        $this->handleArticleShareMerge();
//        $this->tempInitArticleShareRewardNewRule();
//        $this->handleAttn();
//        $start = $input->getArgument('start');
//        $end = $input->getArgument('end');
//        $this->inserCircle();
//
//        $this->handleCircleHistoryDataToMonth((int)$start, (int)$end);
//        $this->createTable();

        /*
        $queueData = [
            'uid' => 200068,
            'title' => '测试邀请明细',
            'content' => '测试邀请明细',
            'from' => '',
            'reward_type' => 2,
            'alert_content' => '测试邀请明细'
        ];
        $string = 'push_34';
        Queue::push('\app\admin\job\PushHandle', $string, 'PushHandle');
        */
        $this->resetAttnTimes();
        $this->resetAttnList();
    }

    //处理attn非-1数据
    public function handleAttn() {
        set_time_limit(3600);
        $this->output->writeln('handleAttn----start----');
        $start = get_millisecond();
        $pageSize = 1000;
        for ($i = 0; $i < 10; $i++) {
            $db = db('user_attn_user_' . $i);
            $lastId = 0;
            do {

                $data = $db->field('id,cid,uid,pid,attn_time,status')->where('id', '>', $lastId)->limit($pageSize)->select();
                if ($data) {
                    $lastId = $data[count($data) - 1]['id'];
                    foreach ($data as $value) {
                        if (strpos($value['cid'], -1) === false) {
                            $db->where('id', $value['id'])->delete();
                            $this->output->writeln('handleAttn,handle,db:' . $i . ',id:' . $value['id'] . ',data:' . json_encode($value));
                        }
                    }
                }
            } while (!empty($data) && $lastId);
        }
        $end = get_millisecond();
        $this->output->writeln('handleAttn----end----,exe_time:' . ($end - $start));
    }

    //普通收益
    protected function handleArticleShareMerge() {
        set_time_limit(3600);
        $start = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s') . 'handleArticleShareMerge,-----start----');
        for ($i = 0; $i < 10; $i++) {
            $db = db('article_share_reward_merge_log_' . $i);
            $db2 = db('article_share_reward_record_' . $i);
            $page = 1;
            $count = 1000;
            do {
                $data = $db
                    ->field('uid,aid')
                    ->limit(($page - 1) * $count, $count)
                    ->select();
                $page++;
                if ($data) {
                    foreach ($data as $value) {
                        $first = $db2
                            ->field('uid,aid,c_time')
                            ->where('uid', $value['uid'])
                            ->where('aid', $value['aid'])
                            ->order('c_time asc')
                            ->find();
                        if ($first) {
                            $this->handleMerge2($value['uid'], $value['aid'], $first['c_time']);
                        }
                    }
                }
            } while (!empty($data));

        }

        $end = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s') . 'handleArticleShareMerge,-----end----,exe_time:' . ($end - $start));
    }

    protected function handleMerge2($uid, $aid, $c_time) {
        $db = db('article_share_reward_merge_log_' . $uid % 10);
        $exists = $db
            ->where('uid', $uid)
            ->where('aid', $aid)
            ->find();
        if ($exists && $c_time !== $exists['c_time']) {
            $this->output->writeln(date('Y-m-d H:i:s') . 'fix,c_time,uid:' . $uid . ',aid:' . $aid . ',id:' . $exists['id']);
            $update['c_time'] = $c_time;
            $db->where('uid', $uid)
                ->where('aid', $aid)
                ->update($update);
        }
    }

    //补贴收益
    public function handleSubsidy() {
//        set_time_limit(3600);
//        $start = get_millisecond();
//        $this->output->writeln(date('Y-m-d H:i:s') . 'handleSubsidy,-----start----');
//        $j = 0;
//
//        $page = 1;
//        $count = 500;
//        do {
//            $data = db('users_article_share_subsidy_detail_record')
//                ->field('uid,aid,subsidy_coin as coin,c_time')
//                ->limit(($page - 1) * $count, $count)
//                ->select();
//            $page++;
//            if ($data) {
//                foreach ($data as $value) {
//                    $j++;
//                    $this->handleMerge($value['uid'], $value['aid'], $value['coin'], $start, $value['c_time'], $value['c_time']);
//                }
//            }
//        } while (!empty($data));
//
//
//        $end = get_millisecond();
//        $this->output->writeln(date('Y-m-d H:i:s') . 'handleSubsidy,-----end----,exe_time:' . ($end - $start) . ',handle_num:' . $j);
    }


    protected function handleMerge($uid, $aid, $coin, $now, $c_time, $m_time) {
//        $db = db('article_share_reward_merge_log_' . $uid % 10);
//        $exists = $db
//            ->where('uid', $uid)
//            ->where('aid', $aid)
//            ->find();
//        if ($exists) {
//            $update['m_time'] = $now;
//            $update['c_time'] = $now;
//            if ($c_time < $exists['c_time']) {
//                $update['c_time'] = $c_time;
//            }
//            if ($m_time > $exists['m_time']) {
//                $update['m_time'] = $m_time;
//            }
//            $db->where('uid', $uid)
//                ->where('aid', $aid)
//                ->exp('coin', 'coin+' . $coin)
//                ->update($update);
//        } else {
//            $insertWalletData['uid'] = $uid;
//            $insertWalletData['aid'] = $aid;
//            $insertWalletData['coin'] = $coin;
//            $insertWalletData['c_time'] = $now;
//            $insertWalletData['m_time'] = $now;
//            $db->insertGetId($insertWalletData);
//        }
    }

    //修复推荐补贴，写入log没写入wallet数据
    protected function fixWallet() {
//        $data = db('users_wallet_log')
//            ->where('type', 17)
//            ->where('coin', '>', 0)
//            ->select();
        $sql = "select sum(coin) as coin,uid from users_wallet_log where type=17 and coin>0 group by uid";
        $data = Db::query($sql);
        if ($data) {
            $now = get_millisecond();
            $this->output->writeln('写入log没写入wallet数据,select data:' . json_encode($data));

            $coin_array = array_column($data, 'coin');
            $coin_sum = array_sum($coin_array);
            $this->output->writeln('金币总差额:' . $coin_sum);

            $walletDb = db('users_wallet');
            foreach ($data as $value) {
                $this->output->writeln('handle,uid:' . $value['uid'] . ',coin:' . $value['coin']);
                $exists = $walletDb->where('uid', $value['uid'])->find();
                if ($exists) {
                    $this->output->writeln('handle,修改之前，wallet数据,walletId:' . $exists['users_wallet_id'] . ',uid:' . $exists['uid'] . ',total_coin:' . $exists['total_coin'] . ',balance_coin:' . $exists['balance_coin']);

                    $walletDb->where('uid', $value['uid'])->exp('total_coin', 'total_coin+' . $value['coin'])->exp('balance_coin', 'balance_coin+' . $value['coin'])->update(['update_time' => $now]);
                } else {
                    $this->output->writeln('handle,insert wallet,uid:' . $value['uid'] . ',coin:' . $value['coin']);

                    $walletDb->insertGetId([
                        'uid' => $value['uid'],
                        'total_coin' => $value['coin'],
                        'balance_coin' => $value['coin'],
                        'create_time' => $now,
                        'update_time' => $now,
                    ]);
                }
            }
        }
    }

    protected function test(Input $input, Output $output) {
//        # 第一步，注释线上 articleRecHandle 脚本 和 articleRecListUpdate 脚本，等待当前运行中的阻塞脚本自动终止后，再启动第二步
//        # 第二步，上线当前 Test 脚本，运行将 user_rec_article 中数据按规则写入到已经建好的10个分表中，并更新到相关 redis1 统计中。
//        $redis1 = Cache::store();
//        $list = Db::table('user_rec_article')->select();
//        foreach ($list as $v) {
//            $new_tab = 'user_rec_article_' . ($v['uid'] % 10);
//            Db::execute("INSERT INTO `" . $new_tab . "` (`uid`,`aid`,`rec_time`) SELECT `uid`,`aid`,`rec_time` FROM user_rec_article WHERE id = " . $v['id']);
//
//            $redis1->zAdd(REDIS_KEY_ARTICLE_REC_USER_LIST . ':' . $v['aid'], $v['rec_time'], $v['uid']);
//        }
//        # 第三步，上线 Admin、Api 二个项目的程序
//        # 第四步，去掉线上 articleRecHandle 脚本的注释。
//        # 第五步，加入新脚本 articleRecListRouteUpdate 替换掉之前的 articleRecListUpdate 脚本。


//        # 第一步，注释线上 articleRecListRouteUpdate 脚本，等待当前运行中的阻塞脚本自动终止后，再启动第二步
//        # 第一步，执行脚本
//        $list = Db::table('user_attn_user')->select();
//        foreach ($list as $v) {
//            $new_tab = 'user_attn_user_' . ($v['uid'] % 10);
//            Db::execute("INSERT INTO `" . $new_tab . "` (`uid`,`pid`,`attn_time`,`status`) SELECT `uid`,`pid`,`attn_time`,`status` FROM user_attn_user WHERE id = " . $v['id']);
//        }
//        # 第三步，上线 Admin、Api 二个项目的程序
//        # 第四步，去掉线上 articleRecListRouteUpdate 脚本的注释。


//        # 恢复文章推荐次数与最后一次推荐时间
//        for ($i = 0; $i <= 9; $i++) {
//            $rec_list = db('user_rec_article_' . $i)->select();
//            foreach ($rec_list as $v) {
//                if ($info = db('article_extend')->where('aid', $v['aid'])->find()) {
//                    if ($info['rec_d_times'] == 0) {
//                        Db::execute("UPDATE `article_extend` SET `rec_d_times` = 1, `rec_d_time` = " . $v['rec_time'] . " WHERE `aid` = " . $v['aid']);
//                    } else {
//                        if ($info['rec_d_time'] >= $v['rec_time']) {
//                            Db::execute("UPDATE `article_extend` SET `rec_d_times` = `rec_d_times` + 1 WHERE `aid` = " . $v['aid']);
//                        } else {
//                            Db::execute("UPDATE `article_extend` SET `rec_d_times` = `rec_d_times` + 1, `rec_d_time` = " . $v['rec_time'] . " WHERE `aid` = " . $v['aid']);
//                        }
//                    }
//                }
//            }
//        }

//        # 更新文章表中的来源 url
//        $max_aid = 304245;
//        $list = db('article')->field('aid,title,source_id')->whereBetween('aid', [0, 57680])->select();
//        foreach ($list as $v) {
//            $e_name = db('source')->where('source_id', $v['source_id'])->value('e_name');
//            $url = db('article_' . $e_name . '_raw')->where('title', $v['title'])->where('is_t', 1)->value('url');
//            if ($url) {
//                db('article')->where('aid', $v['aid'])->update(['source_url' => $url]);
//            }
//        }

//        # 更新文章推荐次数缓存
//        $list = db('article_extend')->field('aid,rec_d_times')->where('rec_d_times', '>', 0)->select();
//        $redis = Cache::store();
//        foreach ($list as $v) {
//            $redis->zIncrby(REDIS_KEY_ARTICLE_REC_NUM_LIST, $v['rec_d_times'], $v['aid']);
//        }

//        # 更新文章推荐时间
//        $redis = Cache::store();
//        $redis_list = $redis->zRevRangeByScore(REDIS_KEY_ARTICLE_REC_NUM_LIST, '+inf', '-inf', array('withscores' => TRUE));
//        foreach ($redis_list as $k => $v) {
//            $rec_d_time = $redis->zRevRangeByScore(REDIS_KEY_ARTICLE_REC_USER_LIST . ':' . $k, '+inf', '-inf', array('withscores' => TRUE, 'limit' => array(0, 1)));
//            $rec_d_time = reset($rec_d_time);
//            $redis->zAdd(REDIS_KEY_ARTICLE_REC_TIME_LIST, $rec_d_time, $k);
//        }

//        # 同步users 用户 到 users_extend
//        $list = db('users')->field('uid')->order('uid', 'asc')->select();
//        foreach ($list as $v) {
//            if (!db('users_extend')->where('uid', $v['uid'])->find()) {
//                echo $v['uid'] . "\n";
//                #db('users_extend')->insert(['uid' => $v['uid']]);
//            }
//        }

//        # 同步 我同好的人数
//        $list = db('users')->field('uid')->order('uid', 'asc')->select();
//        foreach ($list as $v) {
//            // 查出当前的同好人数
//            $old_attn_times = db('users_extend')->where('uid', $v['uid'])->value('attn_times');
//            // 我同好的人数
//            $attn_times = db('user_attn_user_' . $v['uid'] % 10)->where('uid', $v['uid'])->count();
//            if ($old_attn_times != $attn_times) {
//                echo $v['uid'] . '_' . $old_attn_times . '_' . $attn_times . "\n";
//                #db('users_extend')->where('uid', $v['uid'])->update(['attn_times' => $attn_times]);
//            }
//        }

//        # 同步 与被同好的人数
//        $list = db('users')->field('uid')->order('uid', 'asc')->select();
//        foreach ($list as $v) {
//            // 查出当前的同好人数
//            $old_attn_d_times = db('users_extend')->where('uid', $v['uid'])->value('attn_d_times');
//
//            // 时间被同好的人数
//            $attn_d_times = 0;
//            for ($i = 0; $i < 10; $i++) {
//                $attn_d_times += db('user_attn_user_' . $i)->where('pid', $v['uid'])->count();
//            }
//            if ($old_attn_d_times != $attn_d_times) {
//                echo $v['uid'] . '_' . $old_attn_d_times . '_' . $attn_d_times . "\n";
//                #db('users_extend')->where('uid', $v['uid'])->update(['attn_d_times' => $attn_d_times]);
//            }
//        }


        # 取消0评0推的账号的双向同好关系 2019-01-29
//        #$list = db('users')->field('uid')->order('uid', 'asc')->limit(0, 500)->select();
//        #$list = db('users')->field('uid')->order('uid', 'asc')->limit(500, 500)->select();
//        #$list = db('users')->field('uid')->order('uid', 'asc')->limit(1000, 500)->select();
//        #$list = db('users')->field('uid')->order('uid', 'asc')->limit(1500, 500)->select();
//        #$list = db('users')->field('uid')->order('uid', 'asc')->limit(2000, 500)->select();
//        #$list = db('users')->field('uid')->order('uid', 'asc')->limit(2500, 500)->select();
//        #$list = db('users')->field('uid')->where('uid', 200066)->select();
//        $i = 1;
//        foreach ($list as $v) {
//            // 找到用户A同好的用户(且没有推荐过文章的)，将这批用户解除双向关系
//            $attn_users = db('user_attn_user_' . $v['uid'] % 10)->field('pid')
//                ->where('uid', $v['uid'])
//                ->order('pid', 'asc')
//                ->select();
//            foreach ($attn_users as $vv) {
//                // 查询pid 推荐文章为0的用户
//                $rec_times = db('users_extend')->where('uid', $vv['pid'])->value('rec_times');
//                if ($rec_times == 0) {
//                    if (!db('users')->field('uid')->where('uid', $vv['pid'])->find()) {
//                        echo '_同好用户不存在:' . $vv['pid'];
//                        // 用户不存在，直接删除
//                        #db('user_attn_user_' . $v['uid'] % 10)->where('uid', $v['uid'])->where('pid', $vv['pid'])->delete();
//                    } else {
//                        // A取消同好B
//                        $value1 = 'cancel_' . $v['uid'] . '_' . $vv['pid'] . '_' . get_millisecond();// cancel_用户ID_取消同好用户ID_取消同好时间
//                        #Queue::push('app\admin\job\UserAttnHandle', $value1, 'UserAttnHandle');
//
//                        if (db('user_attn_user_' . $vv['pid'] % 10)->where('uid', $vv['pid'])->where('pid', $v['uid'])->find()) {
//                            // B取消同好A
//                            $value2 = 'cancel_' . $vv['pid'] . '_' . $v['uid'] . '_' . get_millisecond();// cancel_用户ID_取消同好用户ID_取消同好时间
//                            #Queue::push('app\admin\job\UserAttnHandle', $value2, 'UserAttnHandle');
//                        }
//
//                        echo $i . '_A:' . $value1;
//                        echo '+++++++++++B:' . $value2;
//                        echo "\n";
//                        $i++;
//                    }
//                }
//            }
//        }
    }

    /**
     * 添加运营用户，
     *
     */
    protected function regNewUserInfo(Input $input, Output $output) {
        $ip_int = 0;
        $redis = Cache::store();
        for ($i = 121; $i <= 220; $i++) {
            $data['nickname'] = 'U' . $i;
            //不然手机号会超出位数
            if ($i < 10) {
                $data['mobile'] = '1100000000' . (string)$i;
            } elseif ($i >= 10 && $i < 100) {
                $data['mobile'] = '110000000' . (string)$i;
            } elseif ($i >= 100) {
                $data['mobile'] = '11000000' . (string)$i;
            }

            // 写主表
            $data['random'] = substr(uniqid(rand()), -5);
            $data['reg_ip'] = $ip_int;
            $data['pic'] = DEFAULT_USER_PIC;
            $data['bg_pic'] = DEFAULT_USER_BG_PIC;
            $data['reg_time'] = time();
            $data['type'] = 5;//运营账号
            //halt($data);
            $uid = db('users')->insertGetId($data);
            // 写入扩展表
            $data2['uid'] = $uid;
            $data2['is_cate'] = 1;
            db('users_extend')->insert($data2);

            //将运营账号写入分类表
            $data3['uid'] = $uid;

//            if ($i <= 100) {
//                $data3['users_category_id'] = $i % 10;
//                if ($data3['users_category_id'] == 0) $data3['users_category_id'] = 10;
//            } else {
//                if ($i % 2 == 0) {
//                    $data3['users_category_id'] = 12;
//                } else {
//                    $data3['users_category_id'] = 11;
//                }
//            }

            $data3['users_category_id'] = ($i % 10) + 13;


            $data3['create_time'] = time();
            db('rel_users_category_' . $uid % 10)->insert($data3);
            //将运营账号按分类放入redis集合中，供新用户的兴趣分类使用
            $key_cate_operate_active_list = REDIS_KEY_CATE_OPERATE_ACTIVE_LIST . ':' . $data3['users_category_id'];
            $redis->sAdd($key_cate_operate_active_list, $data3['uid']);
        }
        print_r('---end');
    }

    /**
     * 未选分类的用户选择分类
     */
    protected function selectUserCate(Input $input, Output $output) {
        //获取is_cate = 1
        //$uid_list = db('users_extend')->where('is_cate', 1)->column('uid');
        $uid_list = db('users')->alias('u')
            ->join('users_extend ue', 'u.uid=ue.uid', 'LEFT')
            ->whereIn('u.type', [0, 1])
            ->where('ue.is_cate', 1)
            ->column('u.uid');
        foreach ($uid_list as $uid) {
            $result = db('rel_users_category_' . $uid % 10)->where('uid', $uid)->find();
            if (!$result) {
                print_r('no cate----' . $uid);
                //重置标识符
                //db('users_extend')->where('uid', $uid)->setField('is_cate', '0');
                //删除登录态
                //db('users_session')->where('uid', $uid)->delete();
            }
        }
    }

    /**
     * 检查用户信息是否是默认数据
     */
    protected function checkUserInfoStatus(Input $input, Output $output) {
        $start_time = get_millisecond();
        $output->writeln(date('Y-m-d H:i:s', time()) . " checkUserInfoStatus Command : === start");

        $offset = 0;
        do {
            $users_list = Db::table('users')->field('uid,nickname,pic')->order('uid', 'asc')->limit($offset, 500)->select();
            if (!$users_list) break;
            //$output->writeln(json_encode($users_list));

            foreach ($users_list as $user) {
                $user_info_status = ['nickname' => 2, 'pic' => 2];
                if (preg_match('/^U/', $user['nickname'])) $user_info_status['nickname'] = 0;
                if ($user['pic'] == DEFAULT_USER_PIC) $user_info_status['pic'] = 0;
                $str_user_info_status = json_encode($user_info_status);
                db('users_extend')->where('uid', $user['uid'])->update(['user_info_status' => $str_user_info_status]);
                $output->writeln(date('Y-m-d H:i:s', time()) . " checkUserInfoStatus Command : ---uid=" . $user['uid'] . '---' . $str_user_info_status);
            }
            $offset = $offset + 500;
            sleep(1);

        } while ($users_list);

        $end_time = get_millisecond();
        $output->writeln(date('Y-m-d H:i:s', time()) . " checkUserInfoStatus Command : === end exec time " . ($end_time - $start_time) . 'ms');
    }

    //更新他推池
    protected function checkRecList(Input $input, Output $output) {
        $start_time = get_millisecond();
        $output->writeln(date('Y-m-d H:i:s', time()) . " checkUserInfoStatus Command : === start");
        //获取用户选择分类对应文章分类
        $article_cate_list = db('users_category')->column('users_category_id,article_category_id');
        $offset = 0;
        do {
            $uid_list = db('users')->order('uid', 'asc')->limit($offset, 500)->column('uid');
            foreach ($uid_list as $uid) {
                $key = REDIS_KEY_ARTICLE_REC_LIST . ':' . $uid;
                $article_item = Cache::store()->zRevRangeByScore($key, '+inf', '-inf');
                if (!$article_item) continue;
                $users_category_list = db('rel_users_category_' . $uid % 10)->where('uid', $uid)->column('users_category_id');

                if (!$users_category_list) {
                    Cache::store()->zRemRangeByScore($key, '-inf', '+inf');
                    $output->writeln("no cate---uid=" . $uid . '----zRem all');
                } else {
                    //获取此用户选择的文章分类
                    $users_article_category_list = [];
                    foreach ($users_category_list as $k => $cate) $users_article_category_list[] = $article_cate_list[$cate];
                    $output->writeln("-----uid=" . $uid . "-----cate_list---" . json_encode($users_article_category_list));
                    foreach ($article_item as $a_key => $aid) {
                        $c = db('article')->where('aid', $aid)->cache(600)->value('category_id');
                        if (!in_array($c, $users_article_category_list)) {
                            $output->writeln("not in cate---aid=" . $aid);
                            Cache::store()->zRem($key, $aid);
                        }
                    }
                }
            }
            $offset = $offset + 500;

        } while ($uid_list);

        $end_time = get_millisecond();
        $output->writeln(date('Y-m-d H:i:s', time()) . " checkUserInfoStatus Command : === end exec time " . ($end_time - $start_time) . 'ms');
    }

    //更新用户昵称(替换掉中间的空白字符)
    protected function updateUsersNickname() {
        $start_time = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s', time()) . " updateUsersNickname Command : === start");
        $offset = 0;
        do {
            $user_info_list = db('users')->order('uid', 'asc')->limit($offset, 500)->field('uid,nickname')->select();
            foreach ($user_info_list as $user_info) {
                $uid = $user_info['uid'];
                $nickname = $user_info['nickname'];
                $new_nickname = preg_replace("/\s+/", '', $nickname);
                if ($new_nickname != $nickname) {
                    $this->output->writeln("uid=" . $uid . "-----nickname---" . $nickname);
                    $this->output->writeln("uid=" . $uid . "-----nickname---" . $new_nickname);
                    db('users')->where('uid', $uid)->update(['nickname' => $new_nickname]);
                }
            }
            $offset = $offset + 500;
        } while ($user_info_list);

        $end_time = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s', time()) . " updateUsersNickname Command : === end exec time " . ($end_time - $start_time) . 'ms');
    }

    //将task_day_user数据导入users_wallet、users_wallet_log
    protected function guideData() {
        $start_time = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s', time()) . " guideData Command : === start");

        //昨天凌晨的时间戳
        $yest_time_stamp = (float)strtotime(date("Y-m-d", strtotime("-1 day"))) * 1000;

        // 开启事务
        Db::startTrans();
        try {
            $user_info_list = db('task_day_user')->where('current_day_time', '>', $yest_time_stamp)->field('uid,task_income,child_task_income')->select();
            foreach ($user_info_list as $user_info) {
                if ($user_info['task_income'] == 0 && $user_info['child_task_income'] == 0) continue;
                $uid = $user_info['uid'];
                $task_income_coin = $user_info['task_income'] * 100;//任务收入（单位是分）----》金币
                $child_task_income_coin = $user_info['child_task_income'] * 100;//子级任务收入（单位分）----》金币

                //记录收入日志
                $wallet_log_data = [
                    'uid' => $uid,
                    'type' => 2,//任务
                    'coin' => $task_income_coin,
                    'link_id' => 0,
                    'c_time' => get_millisecond()
                ];
                db('users_wallet_log')->insert($wallet_log_data);

                //记录收入日志
                $wallet_log_data = [
                    'uid' => $uid,
                    'type' => 3,//子任务
                    'coin' => $child_task_income_coin,
                    'link_id' => 0,
                    'c_time' => get_millisecond()
                ];
                db('users_wallet_log')->insert($wallet_log_data);
                $this->output->writeln('uid=' . $uid . '-----' . json_encode($wallet_log_data));

                //获取用户钱包,存在则更改数据，不存在则插入数据
                $update_coin = $task_income_coin + $child_task_income_coin;
                $wallet['uid'] = $uid;
                $wallet['update_time'] = get_millisecond();
                if ($users_wallet = db('users_wallet')->where('uid', $wallet['uid'])->find()) {
                    $this->output->writeln('users_sign_in---users_wallet------origin total_coin---' . $users_wallet['total_coin']);
                    db('users_wallet')->where('uid', $wallet['uid'])->exp('total_coin', "total_coin+$update_coin")->exp('balance_coin', "balance_coin+$update_coin")->update(['update_time' => get_millisecond()]);
                    $this->output->writeln('users_sign_in---users_wallet------new data---' . json_encode($wallet));
                } else {
                    $wallet['total_coin'] = $update_coin;
                    $wallet['balance_coin'] = $update_coin;
                    $wallet['create_time'] = $wallet['update_time'];
                    db('users_wallet')->insert($wallet);
                    $this->output->writeln('users_sign_in---users_wallet------new data---' . json_encode($wallet));
                }
            }

            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->writeln("users_sign_in error " . $e->getMessage());
            return 0;
        }

        $end_time = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s', time()) . " guideData Command : === end exec time " . ($end_time - $start_time) . 'ms');
    }


    //分享文章收益新规则
    public function tempInitArticleShareRewardNewRule() {
        set_time_limit(3600);
        $start = get_millisecond();
        $db = db('temp_article_share_reward');
        $dayStart = strtotime(date('Y-m-d 0:0:0', strtotime('-1 day'))) * 1000;
        $dayEnd = strtotime(date('Y-m-d 23:59:59', strtotime('-1 day'))) * 1000;
        $uids = db('article_share_reward_record_log')
            ->field('uid,c_time')
            ->whereBetween('c_time', [$dayStart, $dayEnd])
            ->group('uid')
            ->select();
        Log::info('uids:' . json_encode($uids));

        if ($uids) {
            $dbRewardLog = db('article_share_reward_record_log');
            $subsidyDb = db('users_article_share_subsidy_detail_record');
            foreach ($uids as $user) {
                $rewardCount = $dbRewardLog
                    ->field('uid')
                    ->whereBetween('c_time', [$dayStart, $dayEnd])
                    ->where('uid', $user['uid'])
                    ->count();
                $reward = 0;
                $new_reward = 0;
                if ($rewardCount > 0) {
                    $new_reward = $rewardCount * 3;
                    $reward = $rewardCount * 30;
                }

                //文章数
                $articleList = $dbRewardLog->field('aid')
                    ->where('uid', $user['uid'])
                    ->whereBetween('c_time', [$dayStart, $dayEnd])
                    ->group('aid')
                    ->select();
                $read_article_num = $articleList ? count($articleList) : 0;
                //补贴
                $oldSubsidy = $subsidyDb->where('uid', $user['uid'])
                    ->whereBetween('c_time', [$dayStart, $dayEnd])
                    ->sum('subsidy_coin');
                //新规则补贴
                $newSubsidy = 0;
                $lookUids = $subsidyDb->field('uid,look_uid')
                    ->where('uid', $user['uid'])
                    ->whereBetween('c_time', [$dayStart, $dayEnd])
                    ->group('look_uid')
                    ->select();
                Log::info('uid:' . $user['uid'] . ',look_uids:' . json_encode($lookUids));
                $read_user_num = 0;
                if ($lookUids) {
                    $read_user_num = count($lookUids);
                    $lookUids = array_column($lookUids, 'look_uid');
                    $all_count = 0;
                    foreach ($lookUids as $lookUid) {
                        //找出look_uid 看uid的首篇文章
                        $aid = $subsidyDb
                            ->where('uid', $user['uid'])
                            ->where('look_uid', $lookUid)
                            ->whereBetween('c_time', [$dayStart, $dayEnd])
                            ->order('c_time asc')
                            ->limit(1)
                            ->value('aid');
                        $count = $subsidyDb
                            ->where('uid', $user['uid'])
                            ->where('look_uid', $lookUid)
                            ->where('aid', $aid)
                            ->whereBetween('c_time', [$dayStart, $dayEnd])
                            ->count();
                        $all_count += $count;

                    }
                    $level = round(sqrt(count($lookUids)));
                    $realLevel = $level >= 5 ? 5 : $level;
                    $newSubsidy = $realLevel * $all_count * 90;
                }

                $newSubsidy = $newSubsidy >= 150000 ? 150000 : $newSubsidy;
                $nickname = db('users')->where('uid', $user['uid'])->value('nickname');
                $insertData['uid'] = $user['uid'];
                $insertData['nickname'] = $nickname ? $nickname : '';
                $insertData['coin'] = $reward;
                $insertData['read_user_num'] = $read_user_num;
                $insertData['read_article_num'] = $read_article_num;
                $insertData['new_coin'] = $new_reward;
                $insertData['subsidy'] = $oldSubsidy;
                $insertData['new_subsidy'] = $newSubsidy;
                $insertData['reward_date'] = date('Y-m-d', substr($user['c_time'], 0, 10));
                $insertId = $db->insertGetId($insertData);
                Log::info('insertId:' . $insertId);
            }
        }
        $end = get_millisecond();
        Log::info('历史数据新规则算收益,exe_time:' . ($end - $start));
        echo 'success';

    }


    /**
     * 临时数据 start
     *
     * look_uid 最多可给 $num 人贡献补贴
     *
     *
     * 补贴算法， 等级*系数*次数
     */

    public function tempHandleArticleShareSubsidy() {

        set_time_limit(3600);
        $startTime = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s') . ',tempHandleArticleShareSubsidy start');

        $redis = Cache::store();
        $db = db('users_article_share_subsidy_detail_record');
//        $data = $db->field('look_uid')->whereBetween('c_time', [1567180800000, 1567267199000])->group('look_uid')->select();
//
//        if ($data) {
//            foreach ($data as $k => $v) {
//                $data2 = $db->field('uid')->where('look_uid', $v['look_uid'])->whereBetween('c_time', [1567180800000, 1567267199000])->order('c_time')->select();
//
//                if ($data2) {
//                    $res_uid = [];
//
//                    foreach ($data2 as $uid) {
//                        $res_uid[$uid['uid']] = $uid['uid'];
//                    }
//                    if ($res_uid) {
//                        $res = implode(',', $res_uid);
//                        $redis->hSet('look_uid_for_uids', $v['look_uid'], $res);
//                    }
//
//                }
//            }
//        }


        $data = $db
            ->field('uid')
            ->whereBetween('c_time', [1567180800000, 1567267199000])
            ->group('uid')
            ->order('uid')
            ->select();
        $csv_header = [
            'id', '昵称', '补贴金币', '历史补贴金币'
        ];
        $res_csv_content = [];
        if ($data) {
            foreach ($data as $kk => $uid) {
                $look_uid_res = $db->field('look_uid')
                    ->where('uid', $uid['uid'])
                    ->whereBetween('c_time', [1567180800000, 1567267199000])
                    ->group('look_uid')
                    ->select();


                //查询每个look_uid 前$num 个uid 是否有此uid
                if ($look_uid_res) {
                    $key = 'look_uid_for_uids';
//                    for ($i = 1; $i < 4; $i++) {//循环，当一个look_uid 只可以贡献 1，2，3个uid 时

                    $lookUserNum = 0;//阅读人数，计算等级
                    $readNum = 0;//阅读次数
                    foreach ($look_uid_res as $look) {
                        $uids = $redis->hGet($key, $look['look_uid']);
                        if ($uids) {
                            $uid_arr = explode(',', $uids);
                            $uid_arr_res = array_slice($uid_arr, 0, 3);
                            if (in_array($uid['uid'], $uid_arr_res)) {
                                //人数加1
                                $lookUserNum++;
                                //查询此look_uid 阅读次数
                                $look_num_data = $db->field('read_num')
                                    ->where('uid', $uid['uid'])
                                    ->where('look_uid', $look['look_uid'])
                                    ->whereBetween('c_time', [1567180800000, 1567267199000])
                                    ->order('read_num', 'desc')
                                    ->find();
                                if ($look_num_data) {
                                    $look_num_res = (int)$look_num_data['read_num'] >= 5 ? 5 : (int)$look_num_data['read_num'];
                                    $readNum += $look_num_res;
                                }

                            }

                        }
                    }
                    if ($lookUserNum > 0 && $readNum > 0) {
                        $level = round(sqrt(intval($lookUserNum)));
                        $level = $level >= 5 ? 5 : $level;//最多5级
                        $subsidy = $level * ARTICLE_SHARE_SUBSIDY_RATIO * $readNum;
                        $subsidy = $subsidy >= 300000 ? 300000 : $subsidy;
                        $nickname = db('users')->where('uid', $uid['uid'])->value('nickname');

                        $old = db('users_wallet_log')->where('uid', $uid['uid'])
                            ->where('type', 17)
                            ->whereBetween('c_time', [1567180800000, 1567267199000])->sum('coin');

                    }

                    $res_csv_content[$kk] = [$uid['uid'], $nickname, $subsidy, $old];
                    $this->output->writeln(date('Y-m-d H:i:s') . ',tempHandleArticleShareSubsidy handle,uid:' . $uid['uid']);

//                    }

                }
            }

            $fp = fopen(ROOT_PATH . 'public' . DS . 'uploads/temp201909011728.csv', 'a');
            $header = implode(',', $csv_header) . PHP_EOL;
            $content = '';
            foreach ($res_csv_content as $k => $v) {
                $content .= implode(',', $v) . PHP_EOL;
            }
            $csv = $header . $content;
            fwrite($fp, $csv);
            fclose($fp);
        }

        $endTime = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s') . ',tempHandleArticleShareSubsidy end ,exc_time:' . ($endTime
                - $startTime));

    }


    /**
     * 临时数据 end
     *
     * look_uid 最多可给*人贡献补贴
     */


    //临时数据，昨天的阅读用户id，给多少人阅读，一共阅读多少篇文章、一共阅读多少次

    public function readDataTemp() {

        set_time_limit(3600);
        $start = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s') . ',readDataTemp,start---');

        $resData = [];
        //9月8日数据
        /*
         * 给多少人阅读，一共阅读多少篇文章、一共阅读多少次
         * */
        $dayStart = strtotime(date('2019-09-08 0:0:0')) * 1000;
        $dayEnd = strtotime(date('2019-09-08 23:59:59')) * 1000;
        //user_read_statistics  10张表
        $num = 0;
        for ($i = 0; $i < 10; $i++) {
            $db = db('user_read_statistics_' . $i);
            $allLookUids = $db->field('DISTINCT(look_uid)')->whereBetween('c_time', [$dayStart, $dayEnd])->select();
            if ($allLookUids) {
                $allLookUids = array_column($allLookUids, 'look_uid');

                foreach ($allLookUids as $lookUid) {
                    $num++;
                    $this->output->writeln('readDataTemp,handle,look_uid:' . $lookUid . ',num:' . $num);
                    $nickname = db('users')->where('uid', $lookUid)->value('nickname');
                    $countUidData = $db->field('count(DISTINCT(uid)) as count1,count(DISTINCT(aid)) as count2')
                        ->where('look_uid', $lookUid)
                        ->whereBetween('c_time', [$dayStart, $dayEnd])
                        ->find();
                    $countUid = $countUidData ? $countUidData['count1'] : 0;
                    $countAid = $countUidData ? $countUidData['count2'] : 0;
                    $allCount = $db
                        ->where('look_uid', $lookUid)
                        ->whereBetween('c_time', [$dayStart, $dayEnd])
                        ->count();


                    $resData[] = [$lookUid, $nickname, $countUid, $countAid, $allCount];
                }
            }
        }

        $csv_header = [
            'id', '昵称', '阅读人数', '文章数', '次数'
        ];
        $fp = fopen(ROOT_PATH . 'public' . DS . 'uploads/temp201909081125.csv', 'a');
        $header = implode(',', $csv_header) . PHP_EOL;
        $content = '';
        foreach ($resData as $k => $v) {
            $content .= implode(',', $v) . PHP_EOL;
        }
        $csv = $header . $content;
        fwrite($fp, $csv);
        fclose($fp);

        $end = get_millisecond();
        $this->output->writeln(date('Y-m-d H:i:s') . ',readDataTemp,end,exe_time:' . ($end - $start));
        return;
    }

    public function inserCircle() {
        $uid = 1;
        $rec_uid = 2323;
        $aid = 23232323;
        $data = [];
        //rec_uid,aid,rec_time,circle_id,type
        for ($i = 0; $i < 2000; $i++) {
            $data[$i]['uid'] = $uid;
            $data[$i]['rec_uid'] = $rec_uid;
            $data[$i]['aid'] = $aid;
            $data[$i]['rec_time'] = 1568044800000;
            $data[$i]['circle_id'] = 232323232323232;
            $data[$i]['type'] = -1;
        }
        db('circle_user_article_1')->insertAll($data);
    }

    /**
     * 动态时间轴表迁移归档，保留近300条数据
     * 之前的数据按照月份归档
     */
    public function handleCircleHistoryDataToMonth($startI, $endI) {
        set_time_limit(360000);
        $start = get_millisecond();
        $this->output->writeln('handleCircleHistoryData,start---');


        for ($i = $startI; $i < $endI; $i++) {
            $uids = db('circle_user_article_' . $i)->field('DISTINCT(uid)')->select();
            if ($uids) {
                $uids = array_column($uids, 'uid');

                $this->output->writeln('第' . $i . '张表，共' . count($uids) . 'uid');
                foreach ($uids as $uid) {
                    $data = db('circle_user_article_' . $i)
                        ->field('id')
                        ->where('uid', $uid)
                        ->order('id desc')
                        ->limit(300)
                        ->select();
                    if ($data) {
                        $count = count($data);
                        $lastId = $data[$count - 1]['id'];
                        //查询此id之前是否有数据
                        $this->getDataById($lastId, $uid);

                    }
                }

            }

        }


        $end = get_millisecond();
        $this->output->writeln('handleCircleHistoryData,end---,exe_time:' . ($end - $start));
        return;
    }


    //按照时间查询并归档月表
    public function getDataById($lastId, $uid) {
//        $this->output->writeln('处理uid:' . $uid . '此' . $lastId . ',之前的数据');
//        $count = 0;
//        $pageSize = 2000;
//
//        do {
//
//            $data = db('circle_user_article_' . $uid % 10)
//                ->field('id,uid,rec_uid,aid,rec_time,circle_id,type')
//                ->where('uid', $uid)
//                ->where('id', '<', $lastId)
//                ->order('id desc')
//                ->limit($pageSize)
//                ->select();
//            if ($data) {
//                Db::startTrans();
//                try {
//
//                    $count = $count + count($data);
//                    $ids = array_column($data, 'id');
//                    db('circle_user_article_' . $uid % 10)
//                        ->whereIn('id', $ids)->delete();
//
//                    foreach ($data as &$va) {
//                        unset($va['id']);
//                    }
//                    $table = 'circle_user_article_' . $j . '_' . $uid % 10;
//                    $db = db($table);
//                    $data = array_values($data);
//                    $db->insertAll($data);
//                    $this->output->writeln('表写入成功,uid:' . $uid . ',table:' . $table);
//
//
//                    Db::commit();
//                } catch (Exception $e) {
//                    Db::rollback();
//                }
//            }
//        } while (!empty($data));
//
//        $this->output->writeln('处理uid done :' . $uid . ',共' . $count . '数据');


    }


    public function createTable() {
//        $month_table_name = 'users_wallet_log_201910';
//        $exist = Db::query('show tables like "' . $month_table_name . '"');
//        if (empty($exist)) {
//            $this->output->writeln(date('Y-m-d H:i:s', time()) . "table [" . $month_table_name . "] doesn't exist ");
//            $createSql = "CREATE TABLE `$month_table_name` (
//                     `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//                     `uid` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
//                     `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '收支类型（1阅读收益,2任务收益,3好友任务提成,4邀请奖励,5新手红包,6每日签到,7新手任务,8任务卡兑换,9提现,10阅读收益提成,11申诉成功,12推荐收益(wx),13推荐收益(wx朋友圈),14推荐收益(qq),15推荐收益(qq空间),16推荐收益(app内),17推荐补贴,18首次分享,19首次阅读红包,20阅读红包,21充值,22打赏,23被打赏,24首次登陆红包）',
//                     `coin` int(11) NOT NULL DEFAULT '0' COMMENT '金币',
//                     `link_id` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '关联表ID',
//                     `c_time` bigint(11) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
//                     PRIMARY KEY (`id`),
//                     KEY `uid` (`uid`),
//                     KEY `c_time` (`c_time`)
//                    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='用户金币明细表归档表'";
//            Db::execute($createSql);
//            $this->output->writeln(date('Y-m-d H:i:s', time()) . "table [" . $month_table_name . "] created success ");
//        }
    }


    //重置感兴趣和被感兴趣人数(users_extend表)
    public function resetAttnTimes() {
        //set_time_limit(3600);
        $this->output->writeln('resetAttnTimes----start----');
        $start = get_millisecond();
        $pageSize = 1000;
        $lastId = 0;
        do {
            $uid_list = db('users_extend')->where('uid', '>', $lastId)->limit($pageSize)->column('uid');
            if ($uid_list) {
                $lastId = $uid_list[count($uid_list) - 1];
                foreach ($uid_list as $uid) {
                    $this->output->writeln('resetAttnTimes------uid---' . $uid);
                    $update_attn_data = ['attn_times' => 0, 'attn_d_times' => 0];
                    $u_f = db('users_extend')->where('uid', $uid)->update($update_attn_data);//重置数据为0
                    $this->output->writeln('resetAttnTimes----reset----' . $u_f);
                    //获取此用户的圈友数量
                    $circle_friend_num = db('user_attn_user_' . $uid % 10)->where('uid', $uid)->whereNotNull('cid')->count('id');
                    //获取此人被同好的
                    $attn_d_times = 0;
                    for ($i = 0; $i < 10; $i++) {
                        $d_times = db('user_attn_user_' . $i)->where('pid', $uid)->whereNotNull('cid')->count('id');
                        $attn_d_times += $d_times;
                    }
                    //更新users_extend
                    $update_attn_data = ['attn_times' => $circle_friend_num, 'attn_d_times' => $attn_d_times];
                    $u_bool = db('users_extend')->where('uid', $uid)->update($update_attn_data);
                    $this->output->writeln('resetAttnTimes----' . $u_bool . '----' . json_encode($update_attn_data));
                }
            }
        } while (!empty($uid_list) && $lastId);
        $end = get_millisecond();
        $this->output->writeln('resetAttnTimes----end----exe_time:' . ($end - $start));
    }

    //重置被感兴趣人数(userAttendUids键)
    public function resetAttnList() {
        //set_time_limit(3600);
        $this->output->writeln('resetAttnList----start----');
        $start = get_millisecond();
        $redis = Cache::store();
        $pageSize = 1000;
        $lastId = 0;
        do {
            $uid_list = db('users_extend')->where('uid', '>', $lastId)->limit($pageSize)->column('uid');
            if ($uid_list) {
                $lastId = $uid_list[count($uid_list) - 1];
                foreach ($uid_list as $uid) {
                    $this->output->writeln('resetAttnList------uid---' . $uid);
                    $attn_key = REDIS_KEY_USER_ATTEND_UIS . ':' . $uid;
                    $r_f = $redis->rm($attn_key);//删除旧数据
                    $this->output->writeln('resetAttnTimes------' . $uid . '---reset---' . $r_f);
                    //获取感兴趣此用户的人
                    for ($i = 0; $i < 10; $i++) {
                        $fan_list = db('user_attn_user_' . $i)->where('pid', $uid)->whereNotNull('cid')->column('attn_time', 'uid');
                        foreach ($fan_list as $u => $attn_time) {
                            $p_bool = $redis->hSet($attn_key, $u, $attn_time);
                            $this->output->writeln('resetAttnTimes------' . $u . '---add---' . $uid . '----' . $p_bool);
                        }
                    }
                }
            }
        } while (!empty($uid_list) && $lastId);
        $end = get_millisecond();
        $this->output->writeln('resetAttnTimes----end----,exe_time:' . ($end - $start));
    }

}